<template>
  <view class="renew-page">
    <!-- 自定义导航栏 -->
    <CustomNavBar title="续费月卡" />
    
    <!-- 停车场信息 -->
    <view class="parking-info">
      <view class="parking-name">{{ cardData?.parkName }}</view>
      <view class="parking-validity">有效期内免费畅停</view>
    </view>
    
    <!-- 车牌选择 -->
     <view class="selector-container">
      <view class="license-plate-selector">
      <view class="selector-label">车牌号</view>
	  <!-- <car-number-input @numberInputResult="numberInputResult" :defaultStr="defaultNum"></car-number-input> -->
     <view class="selector-value" @click="selectLicensePlate">
        <text>{{ selectedPlate || '请选择' }}</text>
        <text class="selector-arrow" decode>&gt;</text>
      </view>
    </view>

     </view>
    
    
    <!-- 时长选择 -->
    <view class="duration-section">
      <view class="section-title">选择时长</view>
    
      <!-- 1个月选项 -->
      <view class="duration-option" :class="{ 'selected': selectedDuration === 1 }" @click="selectDuration(1)">
        <view class="duration-info">
          <view class="duration-text">1个月</view>
          <view class="price-container">
            <text class="current-price">¥{{ optionPrice(1) }}</text>
          </view>
        </view>
        <!-- <view class="bonus-tag" v-if="selectedDuration === 1">额外赠送1个月停车时长</view> -->
      </view>
      
      <!-- 3个月选项 -->
      <view class="duration-option" :class="{ 'selected': selectedDuration === 3 }" @click="selectDuration(3)">
        <view class="duration-info">
          <view class="duration-text">3个月</view>
          <view class="price-container">
            <text class="current-price">¥{{ optionPrice(3) }}</text>
          </view>
        </view>
      </view>
      
      <!-- 12个月选项 -->
      <view class="duration-option" :class="{ 'selected': selectedDuration === 12 }" @click="selectDuration(12)">
        <view class="duration-info">
          <view class="duration-text">12个月</view>
          <view class="price-container">
            <text class="current-price">¥{{ optionPrice(12) }}</text>
          </view>
        </view>
      </view>
      
      <!-- 自定义选项：点击展开数字输入框（1-35） -->
      <view class="duration-option" :class="{ 'selected': selectedDuration === 'custom' }" @click="selectDuration('custom')">
        <view class="duration-info">
          <view class="duration-text">自定义</view>
          <view class="price-container" v-if="selectedDuration !== 'custom'">
            <text class="current-price">¥{{ optionPrice('custom') }}</text>
          </view>
          <view class="custom-input" v-else @click.stop>
            <uni-easyinput type="number" v-model="customMonths" placeholder="请输入要购买的数量" @blur="validateCustomMonths" />
            <text class="custom-unit">月</text>
          </view>
        </view>
      </view>
            <!-- 自定义选项 -->
      <!-- <view class="duration-option" :class="{ 'selected': selectedDuration === 'custom' }" @click="selectDuration('custom')">
        <view class="duration-info">
          <view class="duration-text">自定义</view>
          <view class="custom-unit">月</view>
        </view>
      </view> -->
    </view>
    
    <!-- 注意事项 -->
    <view class="notice-section">
      <view class="section-title">注意事项</view>
      <view class="notice-list">
        <view class="notice-item">1.停车卡仅限绑定车辆在指定停车场使用。</view>
        <view class="notice-item">2.购买后不支持退款，请确认信息无误。</view>
        <view class="notice-item">3.月卡和天卡的使用规则请参照停车场公示。</view>
      </view>
    </view>
    
    <!-- 协议同意 -->
    <view class="agreement-section">
      <view class="checkbox" :class="{ 'checked': agreedToTerms }" @click="toggleAgreement">
        <view class="checkbox-inner" v-if="agreedToTerms"></view>
      </view>
      <text class="agreement-text">我已阅读并同意</text>
      <text class="agreement-link">《购买停车卡须知》</text>
    </view>
    
    <!-- 底部支付按钮 -->
    <view class="bottom-action">
      <view class="payment-button" @click="proceedToPayment">
        <text>¥{{ currentPrice }} 确认支付</text>
      </view>
      <view class="payment-note">绑定行驶证，并分享月卡可享额外加赠天数</view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import CustomNavBar from '@/components/CustomNavBar.vue'
import { onLoad as onPageLoad } from '@dcloudio/uni-app';
import MyApi from '@/api/my/my.js'
// 响应式数据
const selectedPlate = ref('')
const selectedDuration = ref(1)
const agreedToTerms = ref(false)
const cardData = ref(null)
const selectedCarId = ref(null)
const customMonths = ref(1)

// const priceMap = ref({
//   1: 300,
//   3: 900,
//   12: 3000,
//   'custom': 0
// })

// const originalPriceMap = ref({
//   1: 400,
//   3: 1200,
//   12: 3600,
//   'custom': 0
// })

// 价格计算：基于 cardData.amount * 月份
const baseAmount = computed(() => {
  const amount = parseFloat(cardData.value?.amount)
  return isNaN(amount) ? 0 : amount
})

const optionPrice = (months) => {
  const count = typeof months === 'number' ? months : customMonths.value
  const price = baseAmount.value * count
  return Number.isFinite(price) ? price : 0
}

const currentPrice = computed(() => optionPrice(selectedDuration.value))

// 页面加载时接收参数
onPageLoad((options) => {
  if (options.cardData) {
    try {
      cardData.value = JSON.parse(decodeURIComponent(options.cardData))
      console.log('接收到的卡片数据:', cardData.value)
    } catch (error) {
      console.error('解析卡片数据失败:', error)
    }
  }
})

// 方法
const selectLicensePlate = async () => {
  try {
    uni.showLoading({ title: '加载绑定车辆...' })
    const resp = await MyApi.getBoundVehicles()
    uni.hideLoading()

    const vehicles = Array.isArray(resp) ? resp : (resp?.list || resp?.records || [])

    if (!vehicles || vehicles.length === 0) {
      uni.showToast({ title: '暂无绑定车辆', icon: 'none' })
      return
    }
	console.log("Vehicles: ", vehicles);
    const itemList = vehicles.map(v => v.plate || '未知车牌')

    uni.showActionSheet({
      itemList,
      success: (res) => {
        const idx = res.tapIndex
        selectedPlate.value = itemList[idx]
        selectedCarId.value = vehicles[idx]?.carId || null
      },
      fail: (err) => {
        console.warn('选择车牌取消或失败', err)
      }
    })
  } catch (error) {
    uni.hideLoading()
    console.error('获取绑定车辆失败:', error)
    uni.showToast({ title: '获取绑定车辆失败', icon: 'none' })
  }
}

const selectDuration = (duration) => {
  selectedDuration.value = duration
}

const toggleAgreement = () => {
  agreedToTerms.value = !agreedToTerms.value
}

// 校验自定义月份：仅允许1-35的整数
const validateCustomMonths = () => {
  const raw = customMonths.value
  let val = Number(raw)
  if (!Number.isFinite(val)) val = 1
  val = Math.floor(val)
  if (val < 1) val = 1
  if (val > 35) val = 35
  const changed = String(val) !== String(raw)
  customMonths.value = String(val)
  if (changed) {
    uni.showToast({ title: '请输入1-35的整数', icon: 'none' })
  }
}

const proceedToPayment = () => {
  if (!selectedPlate.value) {
    uni.showToast({
      title: '请选择车牌号',
      icon: 'none'
    })
    return
  }
  
  if (!agreedToTerms.value) {
    uni.showToast({
      title: '请阅读并同意购买须知',
      icon: 'none'
    })
    return
  }

  if (selectedDuration.value === 'custom') {
    validateCustomMonths()
  }
  
  uni.showLoading({
    title: '处理中...'
  })
  
  // 模拟支付流程
  setTimeout(() => {
    uni.hideLoading()
    uni.showToast({
      title: '支付成功',
      icon: 'success'
    })
    
    // 支付成功后返回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  }, 2000)
}
</script>

<style scoped>
.renew-page {
  /* min-height: 100vh; */
  height:1519rpx;
  background-color: #ffffff;
  padding-bottom: 180rpx;
}

/* 停车场信息 */
.parking-info {
  /* background-image: url('../../static/images/activity_pile/bg_car5.png'); */
  background-size: 100%;
  background-position: bottom;
  background-repeat: no-repeat;
  padding: 40rpx 32rpx;
  height: 180rpx;
}

.parking-name {
  font-size: 50rpx;
  font-weight: 540;
  color: #333333;
  margin-bottom: 12rpx;
  letter-spacing: 2rpx;
}

.parking-validity {
  font-size: 28rpx;
  color: #999999;
  padding-top:18rpx;
}

/* 车牌选择器 */
.selector-container {
 padding: 32rpx;
 position: absolute;
 width: 91%;
 top: 17.5%;
}
.license-plate-selector {
  /* margin-top: 20rpx; */
  background-color: #ffffff;
  padding: 32rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 18rpx;
  border: 1rpx solid #00D4AA;
}

.selector-label {
  font-size: 30rpx;
  color: #333333;
}

.selector-value {
  display: flex;
  align-items: center;
  font-size: 30rpx;
  color: #999999;
}

.selector-arrow {
  margin-left: 12rpx;
  color: #cccccc;
}

/* 时长选择 */
.duration-section {
  /* margin-top: 20rpx; */
  background-color: #ffffff;
  padding: 32rpx;
  margin-top:90rpx;
  /* border-radius: 8rpx; */
}

.section-title {
  font-size: 30rpx;
  font-weight: 500;
  color: #333333;
  margin-bottom: 24rpx;
}

.duration-option {
  background-color: #EEFAF9 ;
  border-radius: 8rpx;
  padding: 32rpx;
  margin-bottom: 20rpx;
  position: relative;
}

.duration-option.selected {
  background-color: #ffff ;
  border: 1rpx solid #00D4AA;
}

.duration-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.duration-text {
  font-size: 30rpx;
  color: #333333;
  font-weight: 500;
}

.price-container {
  display: flex;
  align-items: center;
}

.current-price {
  font-size: 36rpx;
  font-weight: 600;
  color: #333333;
  margin-right: 12rpx;
}

.original-price {
  font-size: 28rpx;
  color: #999999;
  text-decoration: line-through;
}

.bonus-tag {
  margin-top: 16rpx;
  background-color: #fff2e8;
  color: #ff6b35;
  font-size: 24rpx;
  padding: 8rpx 16rpx;
  border-radius: 4rpx;
  display: inline-block;
  width:95%;
}

.custom-unit {
  font-size: 30rpx;
  color: #999999;
}

.custom-input {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

/* 注意事项 */
.notice-section {
  /* margin-top: 20rpx; */
  background-color: #ffffff;
  padding: 32rpx;
  border-bottom: 1px solid #DCDFEC ;
  border-top: 1px solid #DCDFEC ;
  /* border-radius: 8rpx; */
}

.notice-list {
  color: #666666;
  font-size: 26rpx;
  line-height: 1.6;
}

.notice-item {
  margin-bottom: 12rpx;
}

/* 协议同意 */
.agreement-section {
  display: flex;
  align-items: center;
  /* padding: 32rpx; */
  padding-left: 140rpx; 
  padding-top:35rpx;
}

.checkbox {
  width: 36rpx;
  height: 36rpx;
  border-radius: 50%;
  border: 2rpx solid #cccccc;
  margin-right: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.checkbox.checked {
  border-color: #00D4AA;
  background-color: #00D4AA;
}

.checkbox-inner {
  width: 20rpx;
  height: 20rpx;
  border-radius: 50%;
  background-color: #ffffff;
}

.agreement-text {
  font-size: 26rpx;
  color: #666666;
}

.agreement-link {
  font-size: 26rpx;
  color: #00D4AA;
}

/* 底部支付按钮 */
.bottom-action {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 24rpx 32rpx;
  background-color: #ffffff;
  /* box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05); */
}

.payment-button {
  background: linear-gradient(135deg, #00D4AA, #00A884);
  border-radius: 60rpx;
  padding: 24rpx;
  text-align: center;
  color: #ffffff;
  font-size: 32rpx;
  font-weight: 600;
  margin-bottom: 12rpx;
}

.payment-note {
  text-align: center;
  font-size: 24rpx;
  color: #000000;
}
</style>